package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.EmailFeignClient;
import com.lagou.edu.utils.Tools;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.Date;
import java.util.Optional;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private AuthCodeDao authCodeDao;
    @Autowired
    private EmailFeignClient emailFeignClient;

    @Override
    public Long save(AuthCode authCode) {
        DateTime now = DateTime.now();
        String randomCode = Tools.getRandomCode(6);
        AuthCode record = this.getUnique(authCode);
        if (record == null) {
            authCode.setCode(randomCode);
            authCode.setCreateTime(now.toDate());
            authCode.setExpireTime(now.plusMinutes(10).toDate());
            AuthCode code = authCodeDao.save(authCode);
            ModelMap modelMap = emailFeignClient.sendEmail(authCode);
            System.out.println(modelMap);
            return code.getId();
        } else {
            // 是否超过一分钟
            Seconds seconds = Seconds.secondsBetween(new DateTime(record.getCreateTime()), new DateTime(new Date()));
            if (seconds.getSeconds() >= 60) {
                record.setCode(randomCode);
                record.setCreateTime(now.toDate());
                record.setExpireTime(now.plusMinutes(10).toDate());
                AuthCode save = authCodeDao.save(record);
                ModelMap modelMap = emailFeignClient.sendEmail(record);
                return save.getId();
            } else {
                return 0L;
            }
        }
    }

    @Override
    public AuthCode getUnique(AuthCode authCode) {
        Example<AuthCode> example = Example.of(authCode);
        Optional<AuthCode> one = authCodeDao.findOne(example);
        return one.orElse(null);
    }

}
